package com.listen.service.impl;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.listen.common.Base64;
import com.listen.common.HttpClientUtil;
import com.listen.vo.Selection;

public class GanzhouServiceImpl {
	String loginurl = "http://www.gzjspxw.cn:8083/QFWebservice.asmx/GetJson";
	String password = "111111";
	List<String> msgList = null;
	private Map<String,Object> cookieMap = new HashMap<>();
	private Map<String,Object> parmMap = new TreeMap<>();
	int endFlag = 0;
	
	public static void main(String[] args) {
		GanzhouServiceImpl instance = new GanzhouServiceImpl();
		try {
			String code = "360721199408168070";
			String[] codes = code.split(",");
			for(int j=0;j<1;j++){
				instance.endFlag = 0;
				for(int i = 0;i<codes.length;i++){
					instance.login(codes[i]);
				}
				System.out.println(instance.endFlag);
				if(instance.endFlag == codes.length)
					break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	public void login(String code) throws Exception{
		String pwstr = code+"###"+password+"###"+10;
		String wstr = Base64.encode(pwstr, "UTF-8");
    	String wid = Base64.encode("1", "UTF-8");
    	String cid = Base64.encode("singleLogin", "UTF-8");
    	String str = Base64.encode("QFSOFT!@#$&*", "UTF-8");
    	//设置cookie
    	cookieMap.put("dl-style", 3);
    	cookieMap.put("name", URLEncoder.encode("张三","UTF-8"));
    	cookieMap.put("jobsId", 10);
    	cookieMap.put("is_true", 1);
    	cookieMap.put("ticket_num", "");
    	cookieMap.put("ks_time", "");
    	cookieMap.put("bmlb", "B");
    	cookieMap.put("nunchoiceId", 0);
    	cookieMap.put("ustr", "QFSOFT!"+URLEncoder.encode("@#$&*","UTF-8"));
    	//设置parm
    	parmMap.put("wstr", wstr);
    	parmMap.put("wid", wid);
    	parmMap.put("cid", cid);
    	parmMap.put("str", str);
    	String json = getJSON(cookieMap,parmMap);
    	if(json == null)
    		System.out.println("用户"+code+"登录失败");
    	else
    		getVideo(json);
	}
	
	public void getVideo(String json) throws Exception{
		//设置新cookie
		JSONObject js = getJSONObject(json);
		cookieMap.put("name", URLEncoder.encode(js.getString("name"),"UTF-8"));
		cookieMap.put("staffId", js.getInt("staffId"));
		cookieMap.put("IdNumber", js.getString("IdNumber"));
		cookieMap.put("bmlb", js.getString("bmlb"));
    	
    	parmMap.put("wstr", Base64.encode("10", "UTF-8"));
    	parmMap.put("wid", Base64.encode("1", "UTF-8"));
    	parmMap.put("cid", Base64.encode("sel_trainning", "UTF-8"));
    	parmMap.put("str", Base64.encode("QFSOFT!@#$&*", "UTF-8"));
    	//第一次查——查询所有视频信息
    	String jsonStr = getJSON(cookieMap,parmMap);
    	//System.out.println("jsonStr="+jsonStr);
    	if(jsonStr == null)
    		System.out.println("用户"+cookieMap.get("IdNumber")+"查询视频信息失败");
    	else{
    		JSONArray array = JSONArray.fromObject(jsonStr);
    		List<Selection> selList = new ArrayList<>();
    		for(int i = 0;i<array.size();i++){
    			Selection sel = new Selection();
    			JSONObject object = JSONObject.fromObject(array.get(i));
    			sel.setId(object.getInt("id"));
    			sel.setTitle(object.getString("title"));
    			sel.setSection(object.getString("section"));
    			sel.setSectionID(object.getInt("sectionID"));
    			sel.setClassTime(object.getString("classTime"));
    			selList.add(sel);
    		}
    		
    		//第二次查——当前看到第几个视频
    		parmMap.put("wstr", Base64.encode(String.valueOf(js.get("staffId")), "UTF-8"));
    		parmMap.put("cid", Base64.encode("get_kspx_num", "UTF-8"));
    		String kspxspJSON = getJSON(cookieMap,parmMap);
    		//System.out.println(kspxspJSON);
    		JSONObject kspxsp = getJSONObject(kspxspJSON);
    		int kspxsp_num = kspxsp.getInt("kspxsp_num");//当前科目数
    		boolean b = true;
    		if(kspxsp_num>127){
    			b = false;
    			endFlag++;
    		}if(b){
    			//第三次查——查询是否缴费,及可听课时间
        		parmMap.put("cid", Base64.encode("sql_ksmessage", "UTF-8"));
        		String ks_messages_json = getJSON(cookieMap,parmMap);
        		JSONObject jfObject = getJSONObject(ks_messages_json);
        		boolean is_pay =  jfObject.getBoolean("is_pay");
        		listen(is_pay,kspxsp_num,selList);
    		}
    		
    	}
	}
	/***
	 * 听课，修改课件状态
	 */
	public void listen(boolean is_pay,int kspxsp_num,List<Selection> selList) throws Exception{
		try {
			int i = 0;
			if(is_pay){
				if(kspxsp_num > 0)
					i = kspxsp_num-28;
				cookieMap.put("sectionID", i);
				int sectionID = selList.get(i).getSectionID();
				String minutes = selList.get(i).getClassTime();
				int classTime = minute2seconds(minutes);
				String classTimeStr = classTime+"";
				int staffId = (int)cookieMap.get("staffId");
				int jobsId = (int) cookieMap.get("jobsId");
				//第一次查
				parmMap.put("wstr", Base64.encode(String.valueOf(sectionID), "UTF-8"));
		    	parmMap.put("cid", Base64.encode("readnumupdate", "UTF-8"));
		    	getJSON(cookieMap,parmMap);
		    	
		    	//第二次查
		    	parmMap.put("wstr", Base64.encode(staffId+"###"+sectionID, "UTF-8"));
		    	parmMap.put("cid", Base64.encode("i_jl", "UTF-8"));
		    	getJSON(cookieMap,parmMap);
		    	
		    	//第三次查
		    	parmMap.put("wstr", Base64.encode(String.valueOf(staffId), "UTF-8"));
		    	parmMap.put("cid", Base64.encode("i_date_jl", "UTF-8"));
		    	getJSON(cookieMap,parmMap);
		    	
		    	//第四次查
		    	parmMap.put("wstr", Base64.encode(String.valueOf(jobsId), "UTF-8"));
		    	parmMap.put("cid", Base64.encode("sel_video", "UTF-8"));
		    	getJSON(cookieMap,parmMap);
		    	
		    	//第五次查
		    	parmMap.put("wstr", Base64.encode(String.valueOf(staffId), "UTF-8"));
		    	parmMap.put("cid", Base64.encode("get_kspx_num", "UTF-8"));
		    	getJSON(cookieMap,parmMap);
		    	
		    	//第六次查——获取timeid,播放用
		    	parmMap.put("wstr", Base64.encode(staffId+"###"+sectionID, "UTF-8"));
		    	parmMap.put("cid", Base64.encode("u_control_i", "UTF-8"));
		    	String sixthJsonStr = getJSON(cookieMap,parmMap);
		    	JSONObject jfObject = getJSONObject(sixthJsonStr);
		    	int timeid = jfObject.getInt("id");
		    	
		    	//第七次查——获取视频地址
		    	parmMap.put("wstr", Base64.encode(jobsId+"###"+sectionID, "UTF-8"));
		    	parmMap.put("cid", Base64.encode("sel_Article_context", "UTF-8"));
		    	getJSON(cookieMap,parmMap);
		    	
		    	//第八次查——播放
		    	parmMap.put("wstr", Base64.encode(timeid+"", "UTF-8"));
		    	parmMap.put("cid", Base64.encode("play_jl_date", "UTF-8"));
		    	getJSON(cookieMap,parmMap);
		    	
		    	//第九次查——保存进度
		    	parmMap.put("wstr", Base64.encode(staffId+"###"+sectionID+"###"+classTime+"###"+classTimeStr, "UTF-8"));
		    	parmMap.put("cid", Base64.encode("savespjd", "UTF-8"));
		    	getJSON(cookieMap,parmMap);
		    	
		    	//最后一次查——更新状态
		    	String wstr10 = sectionID+"###"+staffId;
		    	parmMap.put("wstr", Base64.encode(wstr10, "UTF-8"));
		    	parmMap.put("cid", Base64.encode("set_kspxsp_num_proc", "UTF-8"));
				
		    	String listenJson = getJSON(cookieMap,parmMap);
		    	JSONObject ljObject = getJSONObject(listenJson);
		    	String msg = (String) ljObject.getString("msg");
		    	int error = ljObject.getInt("error");
		    	if(error==0){
		    		System.out.println("账号："+cookieMap.get("IdNumber")+" 第"+ (i+1) +"个视频"+msg+"可以开始听下一个");
		    	}else{
		    		System.out.println("账号："+cookieMap.get("IdNumber")+" 第"+ (i+1) +"视频播放异常，错误代码:"+error +"----"+msg);
		    	}
		    	Thread.sleep(1000*2);
			}else{
				System.out.println("您尚未缴费！");
			}
		} catch (Exception e) {
			System.out.println("账号="+cookieMap.get("IdNumber")+"您尚未缴费！");
			e.printStackTrace();
		}
	}
	
	/**
	 * 将Map中的cookie转换成Json字符串
	 */
	private String getCookieStr(Map<String,Object> cookieMap){
		StringBuilder cookie = new StringBuilder();
		int i = 0;
		for (String key : cookieMap.keySet()) {
			Object value = cookieMap.get(key);
			if(i==0){
				cookie.append(key+"="+value);
			}else{
				cookie.append(";"+key+"="+value);
			}
			i++;
		}
		return cookie.toString();
	}
	
	/**
	 * 将Map中的parm转换成指定格式字符串
	 */
	private String getParmStr(Map<String,Object> parmMap){
		StringBuilder parm = new StringBuilder();
		int i = 0;
		for (String key : parmMap.keySet()) {
			Object value = parmMap.get(key);
			if(i==0){
				parm.append(key+"="+value);
			}else{
				parm.append("&"+key+"="+value);
			}
			i++;
		}
		return parm.toString();
	}
	
	//发送json请求
	private String getJSON(Map<String,Object> cookieMap,Map<String,Object> parmMap){
		CloseableHttpResponse response = null;
		String cookies = this.getCookieStr(cookieMap);
		String parms = this.getParmStr(parmMap);
		try {
        	HttpPost httpPost = new HttpPost(loginurl);// 创建httpPost
        	httpPost.setHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
        	httpPost.setHeader("X-Requested-With","XMLHttpRequest");
        	httpPost.setHeader("Accept","application/xml, text/xml, */*; q=0.01");
        	httpPost.setHeader("Cookie", cookies);
        	response = HttpClientUtil.getInstance().sendHttpPost(httpPost, parms);
        	int status = response.getStatusLine().getStatusCode();
        	if(status==200){
        		String entityStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            	Document document = DocumentHelper.parseText(entityStr);
            	Element root = document.getRootElement();
            	String json = Base64.decode(root.getText(), "UTF-8");
            	//System.out.println(json);
            	return json;
        	}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HttpClientUtil.getInstance().closeResource(response);
		}
		return null;
	}
	
	private int minute2seconds(String minute){
		String [] parms = minute.split(":");
		if(minute.indexOf(":")>0){
			return Integer.parseInt(parms[0])*60 + Integer.parseInt(parms[1]);
		}else{
			return 	Integer.parseInt(parms[0])*60;
		}
	}
	
	//将JSON字符串解析成对象
	private JSONObject getJSONObject(String jsonStr ){
		try {
			JSONArray array = JSONArray.fromObject(jsonStr);
			return JSONObject.fromObject(array.get(0).toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
